package chen.videoedit;

import android.media.MediaCodec;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * acc音乐添加到视频
 */
public class AACaddVIDEOActivity extends BasisActivity {


    private String audio;
    private MediaExtractor mediaAudioExtractor;
    private int AudioTrack;
    private MediaFormat AudiomediaFormat;
    private String video;
    //
    private MediaExtractor mediaVideoExtractor;
    private int VideoTrack;
    private MediaFormat VideomediaFormat;
    private MediaMuxer mediaMuxer;
    private String path_save;
    private int videoTrackIndex;
    private int audioTrackIndex;
    private long time;

    @Override
    public int setlayoutResID() {
        return R.layout.activity_aacadd_video;
    }

    @Override
    public void initialView(Bundle arg0) {

    }

    @Override
    public void setActivity() {
        audio = Environment.getExternalStorageDirectory() + "/audio.aac";//音频文件路径
        video = Environment.getExternalStorageDirectory() + "/test.mp4";//视频文件路径
        path_save = Environment.getExternalStorageDirectory() + "/acc_add.mp4";//视频文件路径
        MyThread thread = new MyThread();
        thread.start();
    }

    @Override
    public void onClick(View v) {

    }


    class MyThread extends Thread {
        @Override
        public void run() {
            addAAC();
        }
    }

    private void addAAC() {
        getAudioFormat();
        getVideoFormat();
        isTimeLong();
        initMediaMuxer();
        splitAudio();
        splitVideo();
        mediaMuxer.stop();
        mediaMuxer.release();
    }

    /**
     * 获取时长
     */
    public void isTimeLong() {
        long vt = VideomediaFormat.getLong(MediaFormat.KEY_DURATION);
        long at = AudiomediaFormat.getLong(MediaFormat.KEY_DURATION);
        if (vt >= at) {
            time = at;
        } else {
            time = vt;
        }
    }

    /**
     * 获取音频
     */
    private void getAudioFormat() {
        mediaAudioExtractor = new MediaExtractor();//初始化分类器
        try {
            mediaAudioExtractor.setDataSource(audio);
        } catch (IOException e) {
            Log.e("error", "MediaExtractor音频初始化失败" + e.toString());
        }
        int Acount = mediaAudioExtractor.getTrackCount();
        for (int i = 0; i < Acount; i++) {
            MediaFormat format = mediaAudioExtractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            if (mime.startsWith("audio/")) {
                AudioTrack = i;//音轨
                AudiomediaFormat = format;//音轨格式
                Log.e("lll", format.toString());
            }
        }
    }

    /**
     * 获取视频
     */
    private void getVideoFormat() {
        mediaVideoExtractor = new MediaExtractor();//初始化分类器
        try {
            mediaVideoExtractor.setDataSource(video);
        } catch (IOException e) {
            Log.e("error", "MediaExtractor音频初始化失败" + e.toString());
        }
        int Acount = mediaVideoExtractor.getTrackCount();
        for (int i = 0; i < Acount; i++) {
            MediaFormat format = mediaVideoExtractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            if (mime.startsWith("video/")) {
                VideoTrack = i;//视频
                VideomediaFormat = format;
            }
        }
    }


    /**
     * 初始化合成器
     */
    private void initMediaMuxer() {
        try {
            mediaMuxer = new MediaMuxer(path_save, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
        } catch (IOException e) {
            e.printStackTrace();
        }
        videoTrackIndex = mediaMuxer.addTrack(VideomediaFormat);//为封装器 添加视轨
        audioTrackIndex = mediaMuxer.addTrack(AudiomediaFormat);//为封装器 添加音轨
        mediaMuxer.start();
    }

    /**
     * 读取视轨文件
     */
    private void splitVideo() {

        mediaVideoExtractor.selectTrack(VideoTrack);//选定轨道
        int videoMaxInputSize = VideomediaFormat.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);//获取缓冲最大字节
        int frame = VideomediaFormat.getInteger(MediaFormat.KEY_FRAME_RATE);//帧
        ByteBuffer inputBuffer = ByteBuffer.allocate(videoMaxInputSize);//分配缓冲
        MediaCodec.BufferInfo videoInfo = new MediaCodec.BufferInfo();//获取取出数据描述
        videoInfo.presentationTimeUs = 0;

        //获取源视频相邻帧之间的时间间隔。(1)
        long videoSampleTime = 1000 * 1000 / frame;
        mediaVideoExtractor.seekTo(0, MediaExtractor.SEEK_TO_PREVIOUS_SYNC); //选择起点
        while (true) {
            inputBuffer.clear();
            int sampleSize = mediaVideoExtractor.readSampleData(inputBuffer, 0);
            if (sampleSize < 0) {
                mediaVideoExtractor.unselectTrack(VideoTrack);   //这里一定要释放选择的轨道，不然另一个轨道就无法选中了
                break;
            }
            mediaVideoExtractor.advance();
            long presentationTimeUs = mediaVideoExtractor.getSampleTime(); //获取当前时间戳
            if (presentationTimeUs > time) {  //剪辑时间到了就跳出
                mediaVideoExtractor.unselectTrack(VideoTrack);
                break;
            }
            int sampleFlag = mediaVideoExtractor.getSampleFlags();  //获取帧类型，只能识别是否为I帧(关键帧)
            videoInfo.offset = 0;
            videoInfo.flags = sampleFlag; //是否关键帧
            videoInfo.size = sampleSize;//数据长度
            videoInfo.presentationTimeUs += videoSampleTime;//
            mediaMuxer.writeSampleData(videoTrackIndex, inputBuffer, videoInfo);
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast("视频分离完成");
            }
        });
    }


    /**
     * 音频读取
     */
    private void splitAudio() {
        //  mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 10);//设置帧
        mediaAudioExtractor.selectTrack(AudioTrack);//选定轨道
        int videoMaxInputSize = AudiomediaFormat.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);//获取缓冲最大字节
        ByteBuffer inputBuffer = ByteBuffer.allocate(videoMaxInputSize);//分配缓冲
        MediaCodec.BufferInfo videoInfo = new MediaCodec.BufferInfo();//获取取出数据描述
        videoInfo.presentationTimeUs = 0;

        long videoSampleTime;
        //获取源视频相邻帧之间的时间间隔。(1)
        {
            mediaAudioExtractor.readSampleData(inputBuffer, 0);
            //skip first I frame
            if (mediaAudioExtractor.getSampleFlags() == MediaExtractor.SAMPLE_FLAG_SYNC)
                mediaAudioExtractor.advance();
            mediaAudioExtractor.readSampleData(inputBuffer, 0);
            long firstVideoPTS = mediaAudioExtractor.getSampleTime();
            mediaAudioExtractor.advance();
            mediaAudioExtractor.readSampleData(inputBuffer, 0);
            long SecondVideoPTS = mediaAudioExtractor.getSampleTime();
            videoSampleTime = Math.abs(SecondVideoPTS - firstVideoPTS);
        }
        mediaAudioExtractor.seekTo(0, MediaExtractor.SEEK_TO_PREVIOUS_SYNC); //选择起点
        while (true) {
            int sampleSize = mediaAudioExtractor.readSampleData(inputBuffer, 0);
            if (sampleSize < 0) {
                mediaAudioExtractor.unselectTrack(AudioTrack);   //这里一定要释放选择的轨道，不然另一个轨道就无法选中了
                break;
            }
            long presentationTimeUs = mediaAudioExtractor.getSampleTime(); //获取当前时间戳
            Log.e("lll",presentationTimeUs+"");
            if (presentationTimeUs > time) {  //剪辑时间到了就跳出
                mediaAudioExtractor.unselectTrack(AudioTrack);
                break;
            }
            mediaAudioExtractor.advance();
            videoInfo.size = sampleSize;
            videoInfo.offset = 0;
            videoInfo.presentationTimeUs += videoSampleTime;
            Log.e("lll", "音频");
            mediaMuxer.writeSampleData(audioTrackIndex, inputBuffer, videoInfo);
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast("音频分类完成");
            }
        });

    }


}
